/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CreateChangeUser.java
 *
 * Created on 7-feb-2010, 19:30:32
 */
package View;

import Controller.Controller;
import Model.Rank;
import Model.User;
import Util.StringToHtmlConverter;
import crypto.Crypt;
import java.util.ArrayList;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;

/**
 *
 * @author user
 */
public class CreateChangeUserView extends javax.swing.JInternalFrame {

    User user = null;
    boolean newUser;

    /**
     * Creates new form CreateChangeUser
     */
    public CreateChangeUserView(User user) {
        initComponents();
        this.setTitle("Add User");
        cboType.setModel(new DefaultComboBoxModel(Rank.values()));
        cboType.removeItem(Rank.STAFF);

        if (user != null) {
            this.user = user;
            txtUserName.setText(user.getUsername());
            lblPassword.setText("Change password");
            cboType.setSelectedItem(this.user.getRank());
            this.setTitle("Change User");
            this.newUser = false;
        } else {
            this.user = new User();
            this.newUser = true;
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblUser = new javax.swing.JLabel();
        txtUserName = new javax.swing.JTextField();
        lblPassword = new javax.swing.JLabel();
        cboType = new javax.swing.JComboBox();
        txtPassword = new javax.swing.JPasswordField();
        lblType = new javax.swing.JLabel();
        btnSave = new javax.swing.JButton();
        btnClose = new javax.swing.JButton();
        lblError = new javax.swing.JLabel();
        txtPasswordConformation = new javax.swing.JPasswordField();
        lblPasswordConformation = new javax.swing.JLabel();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setMinimumSize(null);
        setName("Form"); // NOI18N
        setOpaque(true);

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(flyaway.FlyAWayApp.class).getContext().getResourceMap(CreateChangeUserView.class);
        lblUser.setText(resourceMap.getString("lblUser.text")); // NOI18N
        lblUser.setName("lblUser"); // NOI18N

        txtUserName.setText(resourceMap.getString("txtUserName.text")); // NOI18N
        txtUserName.setName("txtUserName"); // NOI18N

        lblPassword.setText(resourceMap.getString("lblPassword.text")); // NOI18N
        lblPassword.setName("lblPassword"); // NOI18N

        cboType.setName("cboType"); // NOI18N

        txtPassword.setText(resourceMap.getString("txtPassword.text")); // NOI18N
        txtPassword.setName("txtPassword"); // NOI18N

        lblType.setText(resourceMap.getString("lblType.text")); // NOI18N
        lblType.setName("lblType"); // NOI18N

        btnSave.setText(resourceMap.getString("btnSave.text")); // NOI18N
        btnSave.setName("btnSave"); // NOI18N
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        btnClose.setText(resourceMap.getString("btnClose.text")); // NOI18N
        btnClose.setName("btnClose"); // NOI18N
        btnClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCloseActionPerformed(evt);
            }
        });

        lblError.setText(resourceMap.getString("lblError.text")); // NOI18N
        lblError.setToolTipText(resourceMap.getString("lblError.toolTipText")); // NOI18N
        lblError.setName("lblError"); // NOI18N

        txtPasswordConformation.setName("txtPasswordConformation"); // NOI18N

        lblPasswordConformation.setText(resourceMap.getString("lblPasswordConformation.text")); // NOI18N
        lblPasswordConformation.setName("lblPasswordConformation"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnSave)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnClose)
                        .addGap(0, 154, Short.MAX_VALUE))
                    .addComponent(lblError, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(lblUser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lblPasswordConformation, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lblPassword, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lblType, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(cboType, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtPasswordConformation, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(txtPassword, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(txtUserName))))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(lblUser))
                    .addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(lblPassword))
                    .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtPasswordConformation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblPasswordConformation))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(cboType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblType))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSave)
                    .addComponent(btnClose))
                .addGap(10, 10, 10)
                .addComponent(lblError, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCloseActionPerformed

    public boolean saveUser() {
        //instantatie invoer
        String userName = txtUserName.getText();
        char[] pw = txtPassword.getPassword();
        String password = new String(pw);
        Rank rank = (Rank) cboType.getSelectedItem();
        ArrayList<String> errorMessages = new ArrayList<>();

        //bewerking invoer
        userName = userName.trim();
        password = password.trim();
        password = Crypt.encrypt(password);

        //validatie invoer
        if (userName.isEmpty()) {
            errorMessages.add("Please enter a username");
        }
        if ((newUser) && (password.isEmpty())) {
            errorMessages.add("Please enter a password");
        }

        if((newUser) && (!txtPassword.getText().equals(txtPasswordConformation.getText()))){
             errorMessages.add("Passwords dont match");
        }
        
        String foundUserName = Controller.Instance().searchUserName(userName);
        if(newUser){    
            if(foundUserName != null){
                errorMessages.add("Username already exsists");
            } 
        } else{
            if(foundUserName != null && !foundUserName.equals(this.user.getUsername())){
                errorMessages.add("You cannot change "+ this.user.getUsername() + " into "+ userName +  " because it already exsists");
            } 
        }
        
        // als validatie niet gelukt stop
        if (!errorMessages.isEmpty()) {
            lblError.setText(StringToHtmlConverter.format(errorMessages));
            return false;
        }

        if (this.newUser) {
            // nieuwe gebruiker aanmaken en opslaan
            user.setUsername(userName);
            user.setPassword(password, true);
            user.setRank(rank);

            if (Controller.Instance().save(user)) {
                JOptionPane.showMessageDialog(this, "User \"" + user.getUsername() + "\" saved");
                return true;
            }
        } else {
            // bestaande gebruiker bijwerken
            user.setUsername(userName);
            if (!password.isEmpty()) {
                user.setPassword(password, true);
            }
            user.setRank(rank);

            if (Controller.Instance().update(user)) {
                JOptionPane.showMessageDialog(this, "User \"" + user.getUsername() + "\" saved");
                return true;
            }
        }
        return false;
    }

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        if (this.saveUser()) {
            this.dispose();
        }
    }//GEN-LAST:event_btnSaveActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnClose;
    private javax.swing.JButton btnSave;
    private javax.swing.JComboBox cboType;
    private javax.swing.JLabel lblError;
    private javax.swing.JLabel lblPassword;
    private javax.swing.JLabel lblPasswordConformation;
    private javax.swing.JLabel lblType;
    private javax.swing.JLabel lblUser;
    private javax.swing.JPasswordField txtPassword;
    private javax.swing.JPasswordField txtPasswordConformation;
    private javax.swing.JTextField txtUserName;
    // End of variables declaration//GEN-END:variables
}
